package com.wzy.mall.web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.mall.model.vo.ResultVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/mall/*")
public class MallFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 设置编码格式
        request.setCharacterEncoding("utf8");
        response.setContentType("text/html;charset=utf8");


        // 设置响应的授权，解决跨域问题
        ServletContext servletContext = request.getServletContext();
        String origin = (String) servletContext.getAttribute("origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");

        if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // /api/mall/order/   只有关于个人中心（订单）的接口需要验证权限，其他全部不需要验证权限
            String requestURI = request.getRequestURI();
            if(requestURI.toLowerCase().contains("/api/mall/order")){
                //验证是否登录
                Object client = request.getSession().getAttribute("client");
                if(client == null){
                    //没有登录  拦截
                    response.getWriter().println(new ObjectMapper().writeValueAsString(ResultVO.error("当前接口仅登录后才可以访问")));
                    return;
                }
            }
        }

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
